# -*- coding: utf-8 -*-            
# @Time : 2025/6/30 17:12
# @FileName: utils.py
# @Target:
import json, codecs, time, os, logging, datetime
from pprint import pprint
from tqdm import tqdm

from logging.handlers import RotatingFileHandler

from .llm import quality_analyze
from .llm import translator
from .llm import cuzu
from .llm import tool


with codecs.open(
        filename='idmi_backend/data_configs/quality_labels_20250627.json',
        mode='r', encoding='utf-8'
) as fr:
    '''
    质量投诉的相关标签体系
    '''
    QUALITY_LABELS = json.load(fp=fr)

with codecs.open(
        filename='idmi_backend/data_configs/cuzu_labels_20250627.json',
        mode='r', encoding='utf-8'
) as fr:
    '''
    Customer Satisfaction 相关的标签体系
    '''
    CUZU_LABELS = json.load(fp=fr)

def makedirs():
    def check_saved_folder(saved_folder):
        if os.path.exists(saved_folder) and os.path.isdir(saved_folder):
            ...
        else:
            os.makedirs(saved_folder)
    # 创建存储数据的wjj
    check_saved_folder(os.getenv('MAIXUN_DATA_SAVED_PATH', 'maixun_fetch/data_saved'))
    # 创建存储日期的文件夹
    check_saved_folder('maixun_fetch/logs')

def makelogger():
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')

    def setRotatingRootLogger(filename, level=logging.INFO):
        handler = RotatingFileHandler(
            filename,
            encoding='UTF-8',
            maxBytes=1000000,
            backupCount=5
        )
        handler.setFormatter(formatter)
        logger = logging.getLogger()
        logger.setLevel(level)
        logger.addHandler(handler)

    setRotatingRootLogger(os.path.join('maixun_fetch/logs', 'fetch_maixun_data_log.log'))


class MAIXUN_INFO:
    @property
    def ak(self):
        HUAWEI_OBS_AK = "HPUA1GZV2JCGWS83QGK3"
        return os.getenv('HUAWEI_OBS_AK', HUAWEI_OBS_AK)

    @property
    def sk(self):
        HUAWEI_OBS_SK = "tnEoaYeIQcPOtFO6pVe9g6PlD4sp7w3zWXOIyNTM"
        return os.getenv('HUAWEI_OBS_SK', HUAWEI_OBS_SK)

    @property
    def endpoint(self):
        HUAWEI_OBS_ENDPOINT = "https://obs.cn-north-4.myhuaweicloud.com/"
        return os.getenv('HUAWEI_OBS_ENDPOINT', HUAWEI_OBS_ENDPOINT)

    @property
    def prefix_path(self):
        prefix_path = "processed_data_downstream_folder"
        return os.getenv('PREFIX_PATH', prefix_path)

    @property
    def bucket_name(self):
        bucket_name = "obs-voc-cssl-post-data-qa"
        return os.getenv('BUCKET_NAME', bucket_name)

    @property
    def FOLDER(self):
        FOLDER = "maixun_fetch/data_saved"
        return FOLDER

maixun_info = MAIXUN_INFO()

def get_yesterday_list():
    yesterday = datetime.date.today() - datetime.timedelta(days=1)
    yesterday = yesterday.strftime("%Y-%m-%d")
    return [yesterday]



def generate_month_dates(year, month):
    """
    获取指定月份的日期数据，并确保所有的日期小于当天
    """
    # 当月第一天
    start_date = datetime.datetime(year, month, 1)

    # 下个月第一天
    if month == 12:
        next_month = datetime.datetime(year + 1, 1, 1)
    else:
        next_month = datetime.datetime(year, month + 1, 1)

    # 生成日期列表
    dates = []
    current = start_date
    while current < next_month and current < datetime.datetime.now():
        dates.append(current.strftime("%Y-%m-%d"))
        current += datetime.timedelta(days=1)
    return dates


def if_complaints_exists(title_zh, text_zh):
    '''
    判断当前是否存在对应的客户抱怨
    '''
    customer_voice = title_zh + text_zh
    if len(customer_voice):
        if_complaint = quality_analyze.if_quality_complaint(
            customer_voice=customer_voice
        )
        if if_complaint == '是':
            return True
        else:
            return False
    else:
        return False

def purchase_year_analyze(
        title_zh,
        text_zh,
        current_date=''
):
    customer_voice = title_zh + text_zh
    purchase_year = tool.purchase_year(
        customer_voice=customer_voice,
        content=current_date
    )
    return purchase_year




class QualityLabel2IntValue:
    def __init__(self):
        self._quality_labels_1_grade = {}
        self._quality_labels_2_grade = {}
        self._quality_labels_3_grade = {}
        for ITEMS_LIST in QUALITY_LABELS:
            quality_label_1 = ITEMS_LIST['quality_label_1']
            quality_label_1_int_value = ITEMS_LIST['int_value']
            self._quality_labels_1_grade[quality_label_1] = quality_label_1_int_value
            ITEMS = ITEMS_LIST['items']
            for ITEM in ITEMS:
                quality_label_2 = ITEM['quality_label_2']
                quality_label_2_int_value = ITEM['int_value']
                self._quality_labels_2_grade[quality_label_2] = quality_label_2_int_value
                items = ITEM['items']
                for item in items:
                    quality_label_3 = item['quality_label_3']
                    quality_label_3_int_value = item['int_value']
                    self._quality_labels_3_grade[quality_label_3] = quality_label_3_int_value

    @property
    def quality_labels_1_grade(self):
        return self._quality_labels_1_grade

    @property
    def quality_labels_2_grade(self):
        return self._quality_labels_2_grade

    @property
    def quality_labels_3_grade(self):
        return self._quality_labels_3_grade


quality_label2int_value = QualityLabel2IntValue()




def sentiment2intvalue(sentiment) -> int :
    if isinstance(sentiment, str) :
        try:
            sentiment = int(sentiment[-1])
            return sentiment
        except Exception as e:
            return 3
    else:
        return 3


def quality_label2int_label(_complaint_tags) :
    '''
    将Quality Label从文字转换为纯数字
    '''
    complaint_tags = []
    for tag in _complaint_tags:
        quality_1 = tag['quality_1']
        quality_2 = tag['quality_2']
        quality_3 = tag['quality_3']

        quality_1_int_value = quality_label2int_value.quality_labels_1_grade[quality_1]
        quality_2_int_value = quality_label2int_value.quality_labels_2_grade[quality_2]
        quality_3_int_value = quality_label2int_value.quality_labels_3_grade[quality_3]

        content_list_zh = tag['content_list']
        content_list_en = []

        for content in content_list_zh :
            content_en = translator.translate_util_zh2en(title=content, text='')['title_en']
            content_list_en.append(content_en)
        sentiment = sentiment2intvalue(tag['sentiment'])
        complaint_tags.append({
            'quality_1': quality_1,
            'quality_2': quality_2,
            'quality_3': quality_3,
            'quality_1_int_value': quality_1_int_value,
            'quality_2_int_value': quality_2_int_value,
            'quality_3_int_value': quality_3_int_value,
            'content_list_zh': content_list_zh,
            'content_list_en': content_list_en,
            'sentiment': sentiment
        })
    return complaint_tags


def quality_preprocessing(title_zh, text_zh):
    customer_voice = title_zh + text_zh
    _complaint_tags = quality_analyze.complaint_analysis(
        customer_voice=customer_voice
    )
    complaint_tags = quality_label2int_label(_complaint_tags)
    return complaint_tags


#######################
# 接下来将对应 Customer Satisfaction 对应的内容放在下面
class CuZuLabel2IntValue:
    def __init__(self):
        self._cuzu_labels_1_grade = {}
        self._cuzu_labels_2_grade = {}
        for ITEMS_DICT in CUZU_LABELS:
            cuzu_label_1 = ITEMS_DICT['cuzu_label_1']
            cuzu_label_1_int_value = ITEMS_DICT['int_value']
            self._cuzu_labels_1_grade[cuzu_label_1] = cuzu_label_1_int_value
            ITEMS = ITEMS_DICT['items']
            for ITEM in ITEMS :
                cuzu_label_2 = ITEM['cuzu_label_2']
                cuzu_label_2_int_value = ITEM['int_value']
                self._cuzu_labels_2_grade[cuzu_label_2] = cuzu_label_2_int_value

    @property
    def cuzu_labels_1_grade(self):
        return self._cuzu_labels_1_grade

    @property
    def cuzu_labels_2_grade(self):
        return self._cuzu_labels_2_grade

cuzulabel2intvalue = CuZuLabel2IntValue()



def cuzu_label2int_label(_cuzu_tags) :
    '''
    将Quality Label从文字转换为纯数字
    '''
    cuzu_tags = []
    for tag in _cuzu_tags:
        feel_1 = tag['feel_1']
        feel_2 = tag['feel_2']

        feel_1_int_value = cuzulabel2intvalue.cuzu_labels_1_grade[feel_1]
        feel_2_int_value = cuzulabel2intvalue.cuzu_labels_2_grade[feel_2]

        content_list_zh = tag['content_list']
        content_list_en = []

        for content in content_list_zh :
            content_en = translator.translate_util_zh2en(title=content, text='')['title_en']
            content_list_en.append(content_en)
        sentiment = sentiment2intvalue(tag['sentiment'])
        cuzu_tags.append({
            'feel_1': feel_1,
            'feel_2': feel_2,
            'feel_1_int_value': feel_1_int_value,
            'feel_2_int_value': feel_2_int_value,
            'content_list_zh': content_list_zh,
            'content_list_en': content_list_en,
            'sentiment': sentiment
        })
    return cuzu_tags

def cuzu_preprocessing(title_zh, text_zh, vehicle):
    customer_voice = title_zh + text_zh
    _cuzu_tags = cuzu.feel_analysis_withvehicle(
        customer_voice=customer_voice,
        vehicle=vehicle
    )
    cuzu_tags = cuzu_label2int_label(_cuzu_tags)
    return cuzu_tags



import os
import time
from typing import Optional, TextIO


class RotatingFileWriter:
    def __init__(self, base_name: str = "data", max_size_mb: int = 1, dir_path: str = "."):
        """
        单个文件记录器，按大小限制自动切换文件

        :param base_name: 基础文件名前缀（如 "data"）
        :param max_size_mb: 单个文件最大大小（单位：MB）
        :param dir_path: 存储目录路径
        """
        self.base_name = base_name
        self.max_size_bytes = max_size_mb * 1024 * 1024  # 转换为字节
        self.dir_path = dir_path
        self.current_file_index = 0
        self.current_file: Optional[TextIO] = None
        self.current_file_size = 0

        # 创建目录（如果不存在）
        os.makedirs(self.dir_path, exist_ok=True)

        # 初始化第一个文件
        self._create_new_file()

    def _create_new_file(self):
        """创建新文件并重置大小计数器"""
        if self.current_file:
            self.current_file.close()

        file_name = f"{self.base_name}_{self.current_file_index:03d}.txt"
        self.current_file_path = os.path.join(self.dir_path, file_name)
        self.current_file = open(self.current_file_path, "a", encoding="utf-8")
        self.current_file_index += 1
        self.current_file_size = os.path.getsize(self.current_file_path) if os.path.exists(self.current_file_path) else 0

    def write(self, data: str):
        """
        写入数据到当前文件，自动切换文件

        :param data: 要写入的数据（字符串）
        """
        data_size = len(data.encode("utf-8"))  # 计算数据大小（字节）
        if self.current_file_size + data_size >= self.max_size_bytes:
            self._create_new_file()  # 文件大小超过限制，切换新文件

        self.current_file.write(data)
        self.current_file.flush()  # 确保数据立即写入磁盘
        self.current_file_size += data_size

    def close(self):
        """关闭当前文件"""
        if self.current_file:
            self.current_file.close()


class DailyRotatingFileWriter:
    def __init__(self, base_name: str = "sql-data", max_size_mb: int = 5, root_dir: str = "maixun_fetch/sql_saved"):
        """
        按天分割文件记录器

        :param base_name: 基础文件名前缀（如 "data"）
        :param max_size_mb: 单个文件最大大小（单位：MB）
        :param root_dir: 根目录（如 "logs"）
        """
        self.base_name = base_name
        self.max_size_mb = max_size_mb
        self.root_dir = root_dir
        self.current_date = None
        self.writer: Optional[RotatingFileWriter] = None

    def _ensure_directory(self, current_date):
        """创建当天的文件夹（如 logs/2023-10-05）"""
        date_dir = os.path.join(self.root_dir, current_date)
        os.makedirs(date_dir, exist_ok=True)
        return date_dir

    def write(self, data: str, current_date: str):
        """
        写入数据到当天的文件夹中，自动切换文件和日期
        :param data: 要写入的数据（字符串）
        """
        current_date = current_date
        if self.current_date != current_date:
            # 日期变更，关闭旧记录器并创建新记录器
            if self.writer:
                self.writer.close()
            self.current_date = current_date
            date_dir = self._ensure_directory(current_date)
            self.writer = RotatingFileWriter(
                base_name=self.base_name,
                max_size_mb=self.max_size_mb,
                dir_path=date_dir
            )
        self.writer.write(data)
        self.writer.write('\r\n')

    def close(self):
        """关闭当前记录器"""
        if self.writer:
            self.writer.close()

writer = DailyRotatingFileWriter()




